﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using LootPoints.Security;
using System.Xml;

namespace LootPoints.Pages
{
    public partial class Login : Page
    {
        protected override void OnInit(System.EventArgs e)
        {
            base.OnInit(e);

            try { if ((bool)Session["logged"] == true) Response.Redirect("~/Pages/Overview.aspx"); }
            catch { /* User isnt logged in, stay on page */ }
        }

        protected void btnForgot_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/PasswordReset.aspx");
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ModelContainer context = new ModelContainer();
                Character character = (from c in context.Character where c.Name == tbUsername.Text select c).FirstOrDefault();
                if (character != null)
                {
                    if (!Hashing.ValidatePassword(tbPassword.Text, character.Password)) lblPassword.Text = "Wrong password...";
                    else
                    {
                        Session["logged"] = true;
                        if (character.Admin)
                        {
                            Session["isadmin"] = true;
                            Session["admin"] = character.Name;
                        }
                        else Session["isadmin"] = false;
                        Response.Redirect("~/Pages/Overview.aspx");
                    }
                }
                else lblUsername.Text = " Does not exist...";
            }
        }
    }
}